package com.njlime.sys.repository;

import com.njlime.core.base.repository.impl.BaseDaoImpl;
import com.njlime.core.helper.PageBean;
import com.njlime.core.utils.StringUtil;
import com.njlime.sys.entities.Role;
import com.njlime.sys.entities.Unit;
import com.njlime.sys.entities.User;
import com.njlime.sys.security.util.UserUtils;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017-7-18.
 */
@Repository
public class UnitDaoImpl extends BaseDaoImpl<Unit> {

    /**
     * 根据用户查询单位列表（数据范围）
     *
     * @param user 用户
     * @return 单位List
     */
    public List<Unit> listByUser(User user) {
        StringBuilder sb = new StringBuilder();
        List<Object> arrList = new ArrayList<>();
        sb.append("select t.* from t_unit t ");
        sb.append("where t.is_del = 0 ");
        //根据角色判断数据范围(此处不包含创建者为自己的单位)
        //dataScopeFilter(user.getId(), sb, arrList, "t", "t");
        StringBuilder data_scope = new StringBuilder();
        for (int i = 0; i < user.getRoleList().size(); i++) {
            Role role = user.getRoleList().get(i);
            if(i == 0){
                data_scope.append(" and (");
            }else{
                data_scope.append(" or ");
            }
            if (Role.DataScope.UNIT_ALL == role.getData_scope()) {
                data_scope.setLength(0);
                arrList.clear();
                break;
            } else if (Role.DataScope.UNIT_AND_CHILD == role.getData_scope()) {
                data_scope.append("( t.id  = ? or t.parent_ids like concat(?,'%') ) ");
                arrList.add(user.getUnit_id());
                arrList.add(user.getUnit().getParent_ids() + user.getUnit_id());
            } else if (Role.DataScope.UNIT_ONLY == role.getData_scope()) {
                data_scope.append("t.id  = ? ");
                arrList.add(user.getUnit_id());
            } else if (Role.DataScope.ROLE_SET_UNIT == role.getData_scope()) {
                data_scope.append("exist (select 1 from t_role_unit where role_id = ? and unit_id = ? ) ");
                arrList.add(role.getId());
                arrList.add(user.getUnit_id());
            }
            if(i == user.getRoleList().size() - 1){
                data_scope.append(") ");
            }
        }
        sb.append(data_scope);
        List<Unit> unitList = findList(sb.toString(), arrList);
        return unitList;
    }

    /**
     * 获取全部单位
     * @return unit列表
     */
    public List<Unit> findAllList(Unit unit) {
        StringBuilder sb = new StringBuilder();
        List<Object> arrList = new ArrayList<Object>();
        sb.append("select * from t_unit t where is_del = 0 ");
        if(unit != null){
            sb.append("and ( t.id  = ? or t.parent_ids like concat(?,'%') ) ");
            arrList.add(unit.getId());
            arrList.add(unit.getParent_ids() + unit.getId());
        }
        List<Unit> unitList = findList(sb.toString(), arrList);
        return unitList;
    }

    /**
     * 根据条件获取分页单位列表
     * @param pageBean 分页实体
     * @param unit 单位实体
     * @return Map列表
     */
    public PageBean list(PageBean pageBean, Unit unit){
        StringBuilder sb = new StringBuilder();
        List<Object> arrList = new ArrayList<Object>();
        sb.append("select t.* from t_unit t ");
        sb.append("where is_del = 0 ");
        if(!StringUtil.isEmpty(unit.getUnit_name())){
            sb.append("and unit_name like concat('%',?,'%')");
            arrList.add(unit.getUnit_name());
        }
        if(unit.getParent_id() != null){
            sb.append("and parent_id = ? ");
            arrList.add(unit.getParent_id());
        }
        if(unit.getStatus() != null){
            sb.append("and status = ? ");
            arrList.add(unit.getStatus());
        }
        dataScopeFilter(UserUtils.getUser().getId(), sb, arrList, "t", "t");
        int num = getListJdbcSize(sb.toString(), arrList);
        pageBean.setTotalCount(num);
        pageBean.setTotalPage(pageBean.getTotalPage());
        if (num > 0) {
            sb.append(" order by t.id desc limit ?,?");
            arrList.add((pageBean.getCurPage() - 1) * pageBean.getPageSize());
            arrList.add(pageBean.getPageSize());
            pageBean.setMapList(getListJdbc(sb.toString(), arrList));
        }
        return pageBean;
    }

    /**
     * 根据名称获取单位
     * @param name
     * @return Map
     */
    public Map<String,Object> getByName(String name){
        StringBuilder sb = new StringBuilder();
        List<Object> arrList = new ArrayList<Object>();
        sb.append("select * from t_unit where unit_name = ? and is_del = 0 ");
        arrList.add(name);
        int num = getListJdbcSize(sb.toString(), arrList);
        if(num > 0){
            return getListJdbc(sb.toString(),arrList).get(0);
        }
        return null;
    }

    /**
     * 编辑单位
     * @param unit
     * @return
     */
    public int updateUnit(Unit unit){
        StringBuilder sb = new StringBuilder();
        List<Object> arrList = new ArrayList<Object>();
        sb.append("update t_unit set update_time = ?,updater = ? ");
        arrList.add(unit.getUpdate_time());
        arrList.add(unit.getUpdater());
        if(!StringUtil.isEmpty(unit.getUnit_name())){
            sb.append(",unit_name = ? ");
            arrList.add(unit.getUnit_name());
        }
        if(!StringUtil.isEmpty(unit.getHead_url())){
            sb.append(",head_url = ? ");
            arrList.add(unit.getHead_url());
        }
        if(!StringUtil.isEmpty(unit.getIntroduction())){
            sb.append(",introduction = ? ");
            arrList.add(unit.getIntroduction());
        }
        if(unit.getParent_id() != null){
            sb.append(",parent_id = ? ");
            arrList.add(unit.getParent_id());
        }
        if(!StringUtil.isEmpty(unit.getParent_ids())){
            sb.append(",parent_ids = ? ");
            arrList.add(unit.getParent_ids());
        }
        if(unit.getStatus() != null){
            sb.append(",status = ? ");
            arrList.add(unit.getStatus());
        }
        if(!StringUtil.isEmpty(unit.getProvince_name())){
            sb.append(",province_name = ? ");
            arrList.add(unit.getProvince_name());
        }
        if(unit.getProvince_id() != null){
            sb.append(",province_id = ? ");
            arrList.add(unit.getProvince_id());
        }
        if(!StringUtil.isEmpty(unit.getCity_name())){
            sb.append(",city_name = ? ");
            arrList.add(unit.getCity_name());
        }
        if(unit.getCity_id() != null){
            sb.append(",city_id = ? ");
            arrList.add(unit.getCity_id());
        }
        if(!StringUtil.isEmpty(unit.getArea_name())){
            sb.append(",area_name = ? ");
            arrList.add(unit.getArea_name());
        }
        if(unit.getArea_id() != null){
            sb.append(",area_id = ? ");
            arrList.add(unit.getArea_id());
        }
        sb.append(" where id = ?");
        arrList.add(unit.getId());
        return updateJdbc(sb.toString(),arrList);
    }

    /**
     * 更新子级状态
     * @param unit
     * @return
     */
    public int updateChildStatus(Unit unit){
        StringBuilder sb = new StringBuilder();
        List<Object> arrList = new ArrayList<Object>();
        sb.append("update t_unit set status = ? where parent_ids like concat(?,'%') ");
        arrList.add(unit.getStatus());
        arrList.add(unit.getParent_ids() + unit.getId() + ",");
        return updateJdbc(sb.toString(),arrList);
    }

    /**
     * 根据父id获取子级单位的数量
     * @param parent_id
     * @return
     */
    public int countByParentId(Integer parent_id){
        StringBuilder sb = new StringBuilder();
        List<Object> arrList = new ArrayList<Object>();
        sb.append("select id from t_unit where parent_id = ? and is_del = 0 ");
        arrList.add(parent_id);
        return getListJdbcSize(sb.toString(),arrList);
    }

    /**
     * 删除单位
     * @param id
     * @return
     */
    public int deleteUnit(Integer id){
        StringBuilder sb = new StringBuilder();
        List<Object> arrList = new ArrayList<Object>();
        sb.append("update t_unit set is_del = 1 where id = ? ");
        arrList.add(id);
        return updateJdbc(sb.toString(),arrList);
    }

    /**
     * 根据角色获取部门
     *
     * @param role_id
     * @return
     */
    public List<Map<String, Object>> getUnitByRole(Integer role_id) {
        StringBuilder sb = new StringBuilder();
        List<Object> arrList = new ArrayList<Object>();
        sb.append("select t.* from t_unit t ");
        sb.append("join t_role_unit ru on  ru.unit_id = t.id ");
        sb.append("join t_role r on r.id = ru.role_id ");
        sb.append("where t.is_del = 0 and r.is_del = 0 and r.id = ? ");
        arrList.add(role_id);
        return getListJdbc(sb.toString(), arrList);
    }

    /**
     * 根据id获取信息
     *
     * @return
     */
    public Map<String,Object> getById(Integer id) {
        StringBuilder sb = new StringBuilder();
        List<Object> arrList = new ArrayList<Object>();
        sb.append("select t.*,p.unit_name parent_name from t_unit t left join t_unit p on p.id = t.parent_id where t.id = ? and t.is_del = 0 ");
        arrList.add(id);
        List<Map<String,Object>> menuList = getListJdbc(sb.toString(), arrList);
        if(menuList != null && menuList.size() > 0){
            return menuList.get(0);
        }
        return null;
    }

}
